package com.yunche.yunchebusiness.ui.fragment

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.alibaba.fastjson.JSONObject
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.base.BaseFragment
import com.yunche.yunchebusiness.base.BaseResponse
import com.yunche.yunchebusiness.base.rx.SchedulerUtils
import com.yunche.yunchebusiness.entity.AccountBookBaseInfo
import com.yunche.yunchebusiness.entity.AccountBookBaseInfoMainEntity
import com.yunche.yunchebusiness.entity.AccountBookEntity
import com.yunche.yunchebusiness.network.RetrofitManager
import com.yunche.yunchebusiness.network.exception.ErrorStatus
import com.yunche.yunchebusiness.network.exception.ExceptionHandle
import com.yunche.yunchebusiness.toRequestBody
import com.yunche.yunchebusiness.ui.activity.accountbook.FinanceDetailActivity
import com.yunche.yunchebusiness.ui.activity.accountbook.OrderDetailActivity
import com.yunche.yunchebusiness.ui.view.YuncheToolBar
import com.yunche.yunchebusiness.utils.ColorDividerItemDecoration
import com.yunche.yunchebusiness.utils.SpannableStringUtils
import com.yunche.yunchebusiness.utils.ToastyUtils
import com.yunche.yunchebusiness.utils.transpager.DateUtils
import com.yunche.yunchebusiness.utils.transpager.ShadowTransformer
import com.yunche.yunchebusiness.utils.transpager.ViewpagerNoRecycleAdapter
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.fragment_account_book.*
import org.jetbrains.anko.textColor
import java.util.*


/**
 * Create by little on 2018/12/20 11:25
 * Email:
 * 账本
 *
 * type  '资金类型(1入账  2,提现)',
remittance_status  打款状态(默认为1-打款中—-2-打款成功—-3—打款失败
status 资金状态(-1 不需要进行审批操作 1.待审批状态 2.审批拒绝  3.审批通过

1.如果status==-1 或 status==3  则显示 remittance_status的状态信息
2.如果status==1 或 status==2  则显示status的状态信息

时间的话显示update_time时间
 */

@SuppressLint("StaticFieldLeak")

class AccountBookFragment : BaseFragment(), ShadowTransformer.PageSelectListener,
    View.OnClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    private var shadowTransformer: ShadowTransformer? = null;//卡片缩放
    private var views = arrayListOf<View>()//卡片布局
    private var viewpagerRecycleAdapter: ViewpagerNoRecycleAdapter? = null; //卡片adapter

    var orders = arrayListOf<AccountBookEntity>()//订单,资金
    var accountDatas = arrayListOf<AccountBookBaseInfo>()//卡片
    var curPage = 1;//当前页数
    var financeCurPage = 1;//当前页数

    var curType: Int = 1;//当前类型,1订单2资金
    var currentPageTime = "";//当前卡片时间
    var startDateStr = "";//开始时间,时间控件
    var endDateStr = "";//结束时间,时间控件


    //订单adapter,简单列表不单建adapter
    private var orderAdapter = object :
        BaseQuickAdapter<AccountBookEntity, BaseViewHolder>(R.layout.item_account_book_order, orders) {
        override fun convert(helper: BaseViewHolder?, item: AccountBookEntity?) {
            if (curType == 1) {//订单

                var modelName = ""
                if (item?.brandName != null) modelName += item.brandName
                if (item?.seriesName != null) modelName += item.seriesName
                if (item?.modelsName != null) modelName += item.modelsName


                helper!!.setText(R.id.tv_car_name, modelName)
                helper.setText(
                    R.id.tv_money_info,
                    SpannableStringUtils.getBuilder((if (item!!.orderStatus == 2) "已返利：" else "待返利：") + item.tenantRebate + "\n")
                        .setForegroundColor(Color.parseColor(if (item.orderStatus == 2) "#3C3C3F" else "#0E6BFC"))
                        .append("总价：" + item.carPrice + "元", mContext)
                        .setForegroundColor(Color.parseColor("#666666"))
                        .create(mContext)
                );
                helper.setText(R.id.tv_from, "渠道：" + item.partnerName)
                helper.setText(R.id.tv_date, item.loanTime)
                helper!!.setText(R.id.tv_car_status, "")

            } else {//资金
                helper!!.setText(R.id.tv_car_name, if (item!!.type == 1) "入账" else "提现")
                var status = ""
                if (item!!.status == -1 || item!!.status == 3) {
                    when (item!!.remittanceStatus) {
                        1 -> {
                            status = "(打款中)"
                        }
                        2 -> {
                            status = "(打款成功)"
                        }
                        3 -> {
                            status = "(打款失败)"
                        }
                    }
                } else {
                    when (item.status) {
                        1 -> status = "(审批中)"
                        2 ->
                            status = "(审批拒绝)"
                    }
                }
                if (status == "(审批拒绝)" || status == "(打款失败)") {
                    helper!!.setTextColor(R.id.tv_car_status, Color.RED)
                    helper!!.getView<TextView>(R.id.tv_money_info).paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                }

                helper!!.setText(R.id.tv_car_status, status)

                var optionMoney = helper.getView<TextView>(R.id.tv_money_info)
                optionMoney.textColor =
                        if (item!!.type == 1) Color.parseColor("#3C3C3F") else Color.parseColor("#FFA21F")
                helper.setText(R.id.tv_money_info, (if (item!!.type == 1) "+" else "-") + item.sum.toString())
                helper.setText(R.id.tv_from, item.approverTime)
                helper.setText(R.id.tv_date, "账户余额： " + item.totalAmount.toString() + "元")
            }
        }
    };

    override fun setLayout(): Int = R.layout.fragment_account_book

    companion object {
        private var fragment: AccountBookFragment? = null
        fun getInstance(): AccountBookFragment {
            if (fragment == null) {
                fragment = AccountBookFragment()
            }
            return fragment!!
        }
    }


    override fun initView() {

        //当前时间
        currentPageTime = DateUtils.getNow("yyyy-MM").replace("-", "");
        startDateStr = currentPageTime;
        endDateStr = currentPageTime;

        //viewPager 设置
        viewPager.pageMargin = 6
        viewPager.offscreenPageLimit = 3

        // ----------   列表
        rv_orders.layoutManager = LinearLayoutManager(activity!!, LinearLayoutManager.VERTICAL, false)
        rv_orders.addItemDecoration(ColorDividerItemDecoration(Color.parseColor("#f1f1f1"), 2));
        rv_orders.adapter = orderAdapter
        orderAdapter.setEnableLoadMore(true)
        orderAdapter.setOnLoadMoreListener(this, rv_orders);
        orderAdapter.setOnItemClickListener { adapter, view, position ->
            var orders = adapter.data as List<AccountBookEntity>
            var bundle = Bundle()
            if (curType == 1) {//订单详情
                var bundle = Bundle()
                bundle.putString("orderId", orders.get(position).orderId)
                openActivityWithBundle(OrderDetailActivity::class.java, bundle)
            } else {//资金详情
                bundle.putLong("id", orders.get(position).id)
                openActivityWithBundle(FinanceDetailActivity::class.java, bundle)
            }
        }

        //  ----------   toolbar
        toolbar_book.yuncheToolbarCallBack = object : YuncheToolBar.YuncheToolbarCallBack {
            override fun onBackClick() {
            }

            override fun onRightClick() {
                var startDate: Calendar = DateUtils.getFormatCalendar("yyyyMM", startDateStr);
                var endDate: Calendar = DateUtils.getFormatCalendar("yyyyMM", endDateStr);
                val timeOption = TimePickerBuilder(activity, OnTimeSelectListener { date, v ->
                    if (date.time > System.currentTimeMillis()) {
                        ToastyUtils.showError("所选日期不能大于当前日期")
                    } else {
                        currentPageTime = DateUtils.getFormatDate(date, "yyyyMM")
                        var index = 0;
                        for (item: AccountBookBaseInfo in accountDatas) {
                            if (currentPageTime.equals(item.time)) {//跳转至当前选中的卡片
                                viewPager.setCurrentItem(index, false)
                                break;
                            }
                            index++;
                        }
                        getData();
                    }
                }).setRangDate(startDate, endDate)
                    .setType(booleanArrayOf(true, true, false, false, false, false))
                    .setLabel("年", "月", "", "", "", "")
                    .build().show()
            }
        }

        //   ----------   切换列表类型
        tv_cur_type.setOnClickListener(this)
        tv_cur_type_finance.setOnClickListener(this)

        refresh.setOnRefreshListener {
            curPage = 1;
            getFinanceBaseInfoList();
        }

    }


    override fun initData() {
        getFinanceBaseInfoList()
    }


    private var compositeDisposable = CompositeDisposable()
    //卡片切换回调更新
    override fun selected(positionTemp: Int, scrollDirection: Int) {
        if (viewPager.currentItem == positionTemp) {//只有当前页才更新
            if (!compositeDisposable.isDisposed) {//取消请求，防止数据混乱
                compositeDisposable.clear()
            }
            currentPageTime = accountDatas.get(positionTemp).time
            getData();
        }
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.tv_cur_type -> {//切换订单和资金明细
                curType = 1
                tv_cur_type.textSize = 16f
                tv_cur_type.paint.isFakeBoldText = true

                tv_cur_type_finance.paint.isFakeBoldText = false
                tv_cur_type_finance.textSize = 12f


                getData()
            }
            R.id.tv_cur_type_finance -> {
                curType = 2
                tv_cur_type.textSize = 12f
                tv_cur_type.paint.isFakeBoldText = false

                tv_cur_type_finance.paint.isFakeBoldText = true
                tv_cur_type_finance.textSize = 16f


                getData()
            }
        }
    }

    override fun onLoadMoreRequested() {
        if (curType == 1) {
            curPage++
        } else {
            financeCurPage++
        }
        getData()
    }

    //列表
    @SuppressLint("CheckResult")
    private fun getData() {
        msv_book.showLoading();
        var http: Observable<BaseResponse<AccountBookBaseInfoMainEntity>>;

        if (curType == 1) {//订单
            http = RetrofitManager.service.getOrderList(
                currentPageTime,
                curPage
            )
        } else {//资金
            var para = JSONObject()
            para["curPage"] = financeCurPage
            para["pageSize"] = 999

            http = RetrofitManager.service.getFinanceList(
                currentPageTime,
                para.toJSONString().toRequestBody()
            );
        }
        var disp = http.compose(SchedulerUtils.ioToMain())
            .subscribe({
                if (curPage == 1) {
                    orderAdapter.data.clear()
                }
                if (it.datas!!.list != null) {
                    orderAdapter.addData(it.datas!!.list)
                }

                if (!it.datas!!.hasNextPage) {
                    orderAdapter.loadMoreEnd();
                } else {
                    orderAdapter.loadMoreComplete()
                }
                if (it.datas!!.total == 0) {
                    msv_book.showEmpty(if (curType == 1) "当前订单为空" else "当资金明细为空")
                } else {
                    msv_book.showContent()
                }
            }, {
                showError(ExceptionHandle.handleException(it))
                ToastyUtils.showError(ExceptionHandle.handleException(it))
            })
        compositeDisposable.add(disp);
    }

    var maxRebate: Double = 0.0//最大返利
    var maxCount: Int = 0//最大售车
    var maxSum: Double = 0.0//最大车款
    //卡片
    @SuppressLint("CheckResult")
    private fun getFinanceBaseInfoList() {
        var rebateList = arrayListOf<Double>()
        var countList = arrayListOf<Int>()
        var sumList = arrayListOf<Double>()
        refresh.isRefreshing = true;
        RetrofitManager.service.getFinanceBaseInfoList(currentPageTime)
            .compose(SchedulerUtils.ioToMain())
            .subscribe({

                if (it.resultCode != ErrorStatus.SUCCESS) {
                    showError(it.message!!)
                    return@subscribe
                }

                refresh.isRefreshing = false;
                accountDatas.clear();
                accountDatas.addAll(it.datas!!)

                //获取最大值
                it.datas!!.forEach {
                    rebateList.add(it.rebate)
                    countList.add(it.count)
                    sumList.add(it.sum)
                }
                maxRebate = Collections.max(rebateList)
                maxCount = Collections.max(countList)
                maxSum = Collections.max(sumList)

                // ----------  TODO 顶部卡片相关  为防止滑动UI异常，放这里（待优化）
                views.clear();
                viewpagerRecycleAdapter = ViewpagerNoRecycleAdapter(activity, views);
                shadowTransformer = ShadowTransformer(viewPager, viewpagerRecycleAdapter);//卡片缩放
                shadowTransformer!!.setMyPageSelectListener(this)

                var currentIndex = 0;//要跳转的卡片位置
                var position = 0;
                views.clear();
                it.datas!!.forEach {
                    it.maxCount = maxCount
                    it.maxSum = maxSum
                    it.maxRebate = maxRebate
                    //初始化所有卡片
                    var layoutF = LayoutInflater.from(context)
                        .inflate(R.layout.item_account_book_main, rootView as ViewGroup, false);
                    if (currentPageTime.equals(it.time)) {
                        currentIndex = position;
                    }
                    viewpagerRecycleAdapter!!.updateBaseInfo(layoutF, it);
                    views.add(layoutF)
                    position++;
                }
                //第一个和最后一个为可选时间区间
                startDateStr = it.datas!!.get(0).time;
                endDateStr = it.datas!!.get(it.datas!!.size - 1).time;
                // ----------   顶部卡片相关
                viewPager.adapter = viewpagerRecycleAdapter
                viewPager.setCurrentItem(currentIndex, false)

            }, {
                refresh.isRefreshing = false;
                ToastyUtils.showError(ExceptionHandle.handleException(it))
                showError(ExceptionHandle.handleException(it))
            })
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            initData()
        }
    }


    private fun showError(msg: String) {
        msv_book.showError(msg)
    }


}




